package net.sudot.chess.business.wechat.message;

import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import net.sudot.chess.business.model.SocialUser;
import net.sudot.chess.business.model.User;
import net.sudot.chess.business.service.SocialUserService;
import net.sudot.chess.business.wechat.api.WechatApiService;
import net.sudot.chess.config.SystemProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.time.temporal.TemporalAccessor;

/**
 * 模版消息
 *
 * @author tangjialin on 2018-04-02.
 */
public abstract class AbstractTemplateMessage implements TemplateMessage {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SystemProperties systemProperties;
    @Resource
    private WechatApiService wechatApiService;
    @Resource
    private SocialUserService socialUserService;

    @Override
    public void send(User user, Object data) {
        SocialUser socialUser = socialUserService.findByUser(wechatApiService.getWxMpConfigStorage().getAppId(), user.getId());
        if (socialUser == null || socialUser.getUniqueId() == null || !socialUser.isSubscribe()) {
            // 未关注微信号的不发送模版消息
            return;
        }
        try {
            WxMpTemplateMessage.WxMpTemplateMessageBuilder messageBuilder = builderTemplateMessage(user, data, systemProperties);
            if (messageBuilder == null) { return; }
            messageBuilder.templateId(getTemplateId()).toUser(socialUser.getUniqueId());
            wechatApiService.getTemplateMsgService().sendTemplateMsg(messageBuilder.build());
        } catch (Exception e) {
            logger.warn("模板消息发送失败:{}", socialUser.getUniqueId(), e);
        }
    }

    /**
     * 包装模版消息内容
     *
     * @param user             发送的用户信息
     * @param data             模板消息填充的数据
     * @param systemProperties 系统属性
     * @return 返回模版消息实例
     */
    protected abstract WxMpTemplateMessage.WxMpTemplateMessageBuilder builderTemplateMessage(User user, Object data, SystemProperties systemProperties);

    /**
     * 格式化时间
     *
     * @param date 需要格式化的时间
     * @return 返回格式化后的时间字符串
     */
    protected String formatDate(TemporalAccessor date) {
        return DATE_TIME_FORMATTER.format(date);
    }

}
